IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'YearsApart')
BEGIN
	PRINT 'Dropping function YearsApart'
	DROP  FUNCTION dbo.YearsApart
END
GO

PRINT 'Creating function YearsApart'
GO

CREATE FUNCTION dbo.YearsApart(@FromDate DATETIME, @ToDate DATETIME)
RETURNS INT
AS
BEGIN
	DECLARE @ret INT
	SET @ret = 0

	IF (@FromDate IS NOT NULL AND @ToDate IS NOT NULL)
	BEGIN
		SET @ret = 
		CASE
                       WHEN @FromDate > @ToDate THEN NULL
                       WHEN DATEPART(day, @FromDate) > DATEPART(day, @ToDate) THEN DATEDIFF(month, @FromDate, @ToDate) - 1
                       ELSE DATEDIFF(month, @FromDate, @ToDate)
               	END / 12
	END

	RETURN  @ret
END
GO
